package com.atguigu.lease.web.app.service.impl;


import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.ThreadLocalLoginUserContext;
import com.atguigu.lease.common.exception.LoginException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.HttpUtils;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.common.utils.VerifyCodeUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.http.HttpResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Autowired
    UserInfoService userInfoService;


    @Override
    public void getCode(String phone) {


        //验证码
        String verifyCode = VerifyCodeUtil.getVerifyCode(6);

        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = "be07796271094ea188b7b9b0a12feb52";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        querys.put("param", "**code**:"+verifyCode+",**minute**:5");

//smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html

        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<String, String>();


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从\r\n\t    \t* https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java\r\n\t    \t* 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        redisTemplate.opsForValue().set(RedisConstant.APP_LOGIN_PREFIX+phone, verifyCode,RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC, TimeUnit.SECONDS);
//        redisTemplate.opsForValue().set(RedisConstant.APP_LOGIN_PREFIX+phone, verifyCode,60*60, TimeUnit.SECONDS);


    }

    @Override
    public String login(LoginVo loginVo) {


        String code = loginVo.getCode();
        String phone = loginVo.getPhone();
        //判空
        if (code == null){
            throw new LoginException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        if (phone ==null){
            throw new LoginException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }


        //校验验证码
        String RedisCode = redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + phone);
        if (!code.equals(RedisCode)){
            throw new LoginException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }else{
            redisTemplate.delete(RedisConstant.APP_LOGIN_PREFIX + phone);
        }


        // 如果用户没注册就注册使用
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper =new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfoOne = userInfoService.getOne(userInfoLambdaQueryWrapper);
        if (userInfoOne ==null){
            UserInfo userInfo =new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setNickname("用户"+loginVo.getPhone().substring(5));
            userInfoService.save(userInfo);
        }

        // 返回token
        assert userInfoOne != null;
        return JwtUtil.createToken(userInfoOne.getId(), userInfoOne.getNickname());
    }

    @Override
    public UserInfoVo getInfo() {
        LoginUser loginUser = ThreadLocalLoginUserContext.getLoginUser();


        UserInfo userInfoServiceById = userInfoService.getById(loginUser.getUserId());

        UserInfoVo userInfoVo =new UserInfoVo();
        BeanUtils.copyProperties(userInfoServiceById,userInfoVo);
        return userInfoVo;
    }
}
